package com.evan.dead;

import java.util.concurrent.TimeUnit;

/**
 * @author huangzhongliang
 * @time 2023/06/09 20:36
 */
public class DeadLockDemo {
    static Object a = new Object();
    static Object b = new Object();

    public static void main(String[] args) {
        //使用隐式的可重入锁(递归锁)
        //    手写一个死锁
        new Thread(() -> {
            //同步代码块
            synchronized (a) {
                System.out.println(Thread.currentThread().getName() + "持有a锁,试图获取b锁中");
                //模拟做业务
                try {
                    TimeUnit.SECONDS.sleep(1);
                } catch (InterruptedException e) {
                    e.printStackTrace();
                }
                synchronized (b) {
                    System.out.println(Thread.currentThread().getName() + "获取到了b锁");
                }
            }

        }, "A").start();


        new Thread(() -> {
            //同步代码块
            synchronized (b) {
                System.out.println(Thread.currentThread().getName() + "持有b锁,试图获取a锁中");
                //模拟做业务
                try {
                    TimeUnit.SECONDS.sleep(1);
                } catch (InterruptedException e) {
                    e.printStackTrace();
                }
                synchronized (a) {
                    System.out.println(Thread.currentThread().getName() + "获取到了a锁");
                }
            }

        }, "B").start();

    }
}
